package com.cb.controller.front.order;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONML;
import org.json.JSONObject;
import org.tempuri.ServiceSoap;

import webservices.alipaydirect.util.UtilDate;

import com.cb.common.enumType.OrderStatus;
import com.cb.common.map.BOrderCommon;
import com.cb.common.map.Constants;
import com.cb.common.webService.ClientService;
import com.cb.common.webapp.context.RequestContext;
import com.cb.core.util.DateUtil;
import com.cb.domain.model.order.BOrder;
import com.cb.domain.model.order.Flight;
import com.cb.domain.model.order.Insurance;
import com.cb.domain.model.order.InsuranceCompany;
import com.cb.domain.model.order.Passenger;
import com.cb.domain.model.order.Policy;
import com.cb.domain.model.user.UserAccount;
import com.cb.domain.service.order.InsuranceCompanyManager;
import com.cb.domain.service.order.PolicyManager;

public class AbeUtil {
	
	protected final static Log logger = LogFactory.getLog(AbeUtil.class);

	public static String changePnr(String result) {

		// String
		// result="<CRS.CommandSet.PNR><Success></Success><Errors/><PNR>HWBKDT</PNR><FlightType>D</FlightType><TicketType>NONE</TicketType><AgentOffice>CAN859</AgentOffice><Passengers><Passenger ElementNo=\"1\" PsgID=\"1\" Name=\"张三\" Type=\"0\" PsgType=\"ADT\" CardType=\"\" CardNo=\"\" Gender=\"\" CarrierCard=\"\" BirthDay=\"\" CarrierPsgID=\"\" Country=\"\" FNNo=\"\" TicketNo=\"\"/></Passengers><Flights><Flight ElementNo=\"2\" ID=\"1\" Type=\"0\" FltType=\"\" Carrier=\"CZ\" Flight=\"3103\" ShareCarrier=\"\" ShareFlight=\"\" BoardPoint=\"CAN\" OffPoint=\"PEK\" Week=\"SA\" DepartureDate=\"2012-06-09\" DepartureTime=\"11:00\" ArriveDate=\"2012-06-09\" ArriveTime=\"14:10\" Class=\"V\" ActionCode=\"HN\" Seats=\"1\" Meal=\"\" Stops=\"\" Avail=\"\" Night=\"\" ETKT=\"E\" Changed=\"\" LinkLevel=\"\" Allow=\"20K\" BoardPointAT=\"\" OffpointAT=\"T2\"/></Flights><Contacts><Contacts No=\"CAN/T CAN/T 020-61223899/CAN MEI YING SHANG LV SERVICE CO.,LTD/LI DU CHAO     ABCDEFG\"/><Contacts No=\"END\"/></Contacts><PNRs><PNR No=\"NVRY1F\" GDS=\"CA\"/></PNRs><TicketNos/><RMKs/><SSRs/><OSIs/><Segments><Segment ElementNo=\"6\" Text=\"RMK AO/ABE/KH-/OP-NN /DT-20120601171246\"/></Segments><TKT ElementNo=\"5\" Type=\"TL\" TimeLimit=\"08:00\" DateLimit=\"2012-06-02\" DateTimeLimit=\"2012-06-02 08:00\" Office=\"CAN859\" Changed=\"N\" Text=\"\" PsgID=\"\"/></CRS.CommandSet.PNR>";
		String pnr = "";
		try {
			JSONObject job = JSONML.toJSONObject(result);
			JSONArray jsonArray = job.getJSONArray("childNodes");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String tagName = jsonObject.getString("tagName");
				if (tagName.equalsIgnoreCase("PNR")) {
					pnr = jsonObject.getString("childNodes");
					pnr = pnr.replaceAll("[\\[\\]]", "").replaceAll("\"", "");
					break;
				}
			}
		} catch (JSONException e) {
			logger.error(e);
			return "";
		}
		logger.info(pnr);
		return pnr;
	}
	
	public static BOrder convertOrder(HttpServletRequest request,PolicyManager policyManager,InsuranceCompanyManager insuranceCompanyManager,String identity) throws Exception{
		
		String policy_id=request.getParameter("policy_id");
		String flight_no=request.getParameter("flight_no");
		String cabin=request.getParameter("cabin");
		String departure_day=request.getParameter("departure_day");
		String departure_city=request.getParameter("departure_city");
		String departure_airport=request.getParameter("departure_airport");
		String departure_time=request.getParameter("departure_time");
		String arrival_city=request.getParameter("arrival_city");
		String arrival_airport=request.getParameter("arrival_airport");
		String arrival_time=request.getParameter("arrival_time");
		String flyTime=request.getParameter("flyTime");
		String tmp=request.getParameter("tmp");
		
		String price=request.getParameter("price");
		String discount=request.getParameter("discount");
		String construction_fee=request.getParameter("construction_fee");
		String fuel_tax=request.getParameter("fuel_tax");
		String child_fuel_tax=request.getParameter("child_fuel_tax");
		String print_price=request.getParameter("print_price");
		String child_print_price=request.getParameter("child_print_price");
		String real_price=request.getParameter("real_price");
		String type=request.getParameter("type");
		String stop=request.getParameter("stop");
		String gx=request.getParameter("gx");
		String child_cangwei=request.getParameter("child_cangwei");
		String flightType=request.getParameter("flightType");
		
		String contact=request.getParameter("contact");
		String contactMob=request.getParameter("contactMob");
		String contactEmail=request.getParameter("contactEmail");
		
		
		String needXC=request.getParameter("needXC");
		String needFP=request.getParameter("needFP");
		String sjr=request.getParameter("sjr");
		String contactTel=request.getParameter("contactTel");
		String address=request.getParameter("address");
		String xcd=request.getParameter("xcd");
		String contactCode=request.getParameter("contactCode");
		
		String insuranceStatistics=request.getParameter("insuranceStatistics");
		String allPriceStr=request.getParameter("allPriceStr");
		String insuranceCuttingPrice=request.getParameter("bxDiscount");
		
		Boolean needPS=false;
		BOrder bOrder=new BOrder();
		
		
		bOrder.setFlightType(1l);
		bOrder.setStatus(BOrderCommon.getOrderStatusMap().get(OrderStatus.BOOK_OK));
		if(StringUtils.isNotBlank(needXC)){
			needPS=true;
			bOrder.setNeedXC(Long.valueOf(needXC));
		}
		if(StringUtils.isNotBlank(needFP)){
			needPS=true;
			bOrder.setNeedFP(Long.valueOf(needFP));
		}
		bOrder.setInsuranceStatistics(Double.valueOf(insuranceStatistics));
		bOrder.setInsuranceCuttingPrice(Long.valueOf(insuranceCuttingPrice));
		bOrder.setXcd(xcd);
		if(needPS){
			String expType=request.getParameter("expType");
			bOrder.setExpType(Long.valueOf(expType));
			bOrder.setNeedPS(1l);
			bOrder.setContactCode(contactCode);
			bOrder.setContactTel(contactTel);
			bOrder.setSjr(sjr);
			bOrder.setAddress(address);
			String xcdPrice=request.getParameter("needXcd");
			bOrder.setXcdPrice(Long.valueOf(xcdPrice));
		}
		
		if(StringUtils.isNotBlank(policy_id)){
		Policy policy=policyManager.get(Long.valueOf(policy_id));
		bOrder.setPolicy(policy);
		}
		UserAccount userAccount=RequestContext.getCurrentUser();
		if(userAccount!=null){
			bOrder.setUserAccount(userAccount);
		}
		bOrder.setNoPay(Long.valueOf(allPriceStr));
//		bOrder.setOrderType(Long.valueOf(flightType));
//		bOrder.setChildPrintPrice(Long.valueOf(print_price));
		bOrder.setChildFaceValue(0l);
		bOrder.setCabinnote("");
		bOrder.setSource("self");
//		bOrder.setPolicy(new Policy());
		bOrder.setPayChannel("");
		bOrder.setContact(contact);
		bOrder.setContactEmail(contactEmail);
		bOrder.setContactMob(contactMob);
		bOrder.setPrice(Long.valueOf(price));
		bOrder.setViewPrice(Long.valueOf(allPriceStr));
		bOrder.setAllPrice(Long.valueOf(allPriceStr));
		bOrder.setChildFaceValue(Long.valueOf(print_price));
//		bOrder.setChildPrintPrice(Long.valueOf(child_print_price));
		bOrder.setConstructionFee(Double.valueOf(construction_fee));
		bOrder.setFuelTax(Double.valueOf(fuel_tax));
		bOrder.setChildFuelTax(Double.valueOf(child_fuel_tax));
		bOrder.setCreateTime(new Date());
		bOrder.setFlightType(1l);
		bOrder.setOrderNo("m"+UtilDate.getOrderNum());
		

		String carrierName=request.getParameter("carrierName"); 
		Set<Flight> flights=new HashSet<Flight>();
		Flight flight=new Flight();
		flight.setCode(flight_no);
		flight.setCabin(cabin);
		flight.setFlightName("");
		flight.setDep(departure_city);
		flight.setArr(arrival_city);
		flight.setDepDay(departure_day);
		flight.setDepTime(departure_time);
		flight.setArrDay(departure_day);
		flight.setArrTime(arrival_time);
		flight.setMileage(Long.valueOf(tmp));
		flight.setFlightTime(flyTime);
		flight.setRealCode("");
		flight.setBoardPointName(departure_airport);
		flight.setOffPointName(arrival_airport);
		flight.setStop(Integer.parseInt(stop));
		flight.setFlightName(carrierName);
		flight.setOrder(bOrder);
		
		flights.add(flight);
		bOrder.setFlights(flights);
		
		Set<Passenger> list=new HashSet<Passenger>();
		

		String ADPprice=request.getParameter("ADPprice");
		String CHDViewprice=request.getParameter("CHDViewprice");
		
		String [] passengerTypes=request.getParameterValues("passengerType");
		String [] passengNames=request.getParameterValues("passengName");
		String [] sexs=request.getParameterValues("sex");
		String [] passengerBirthdays=request.getParameterValues("passengerBirthday");
		String [] cards=request.getParameterValues("card");
		String [] cardNos=request.getParameterValues("cardNo");
		
		String [] bxCounts=request.getParameterValues("bx");
		
		
		String initBx=request.getParameter("initBx");
		String [] bx=request.getParameterValues("bx");
		
		
		
		Double totalFee=0d;
		
		String viewPrice=request.getParameter("viewPrice");
		String ticketPrice=request.getParameter("ticketPrice");
		Boolean isHaveChd=false;
		for (int i = 0; i < passengerTypes.length; i++) {
			Passenger passenger=new Passenger();
			
			passenger.setAgeType(passengerTypes[i]);
			passenger.setName(passengNames[i]);
			passenger.setSex(sexs[i]);
			try {
			if(StringUtils.isNotBlank(passengerBirthdays[i])){
				passenger.setBirthday(DateUtil.convertStringToDate(passengerBirthdays[i]));
			}else{
				String cardNo=cardNos[i];
					String year=cardNo.substring(6,10);
		            String month=cardNo.substring(10,12);
		            String day=cardNo.substring(12,14);
		            passenger.setBirthday(DateUtil.convertStringToDate(year+"-"+month+"-"+day));

			}} catch (ParseException e) {
				// TODO Auto-generated catch block
				logger.equals(e);
			}	
			passenger.setCardType(cards[i]);
			passenger.setCardNum(cardNos[i]);
			passenger.setbOrder(bOrder);
			
			if(passenger.getAgeType().equalsIgnoreCase("NI")){
				passenger.setTicketPtice(Long.valueOf(viewPrice));
				passenger.setFeePrice(Double.valueOf(ticketPrice));
				passenger.setConstructionFee(Long.valueOf(construction_fee));
				passenger.setFuelTax(Long.valueOf(fuel_tax));
				totalFee+=Double.valueOf(construction_fee)+Double.valueOf(fuel_tax);
				//保险
				passenger.setTotalPrice(Double.valueOf(viewPrice)+Double.valueOf(construction_fee)+Double.valueOf(fuel_tax));
			}else if(passenger.getAgeType().equalsIgnoreCase("CHD")){
				isHaveChd=true;
				passenger.setFeePrice(Double.valueOf(1700));
				passenger.setTicketPtice(Long.valueOf(CHDViewprice));
				passenger.setConstructionFee(0l);
				passenger.setFuelTax(Long.valueOf(child_fuel_tax));
				totalFee+=Double.valueOf(child_fuel_tax);
				passenger.setTotalPrice(Double.valueOf(CHDViewprice)+Double.valueOf(child_fuel_tax));
				flight.setCcabin("Y");
			}
			
			String insuranceCompanyId=request.getParameter("insuranceCompanyId");
			
			InsuranceCompany insuranceCompany= insuranceCompanyManager.get(Long.valueOf(insuranceCompanyId));
			if(null!=insuranceCompany){
			
			Long counts=Long.valueOf(bxCounts[i]);
			passenger.setBxPrice(Long.valueOf(initBx)*counts);
			passenger.setBxSource(insuranceCompany.getInsuranceName());
			passenger.setInsuranceCount(counts);
			passenger.setBxName(insuranceCompany.getType());
			
			Set<Insurance> insurances=new HashSet<Insurance>();
			for (int j = 0; j < counts; j++) {
				
				//InsuranceSaver insuranceSaver= factoryInsuranceCreater.createSaver(insuranceCompany.getBxType());
				Insurance insurance=new Insurance();
				insurance.setBxFlight(departure_city+"-"+arrival_city);
				insurance.setPassenger(passenger);
				insurance.setBxStatus(Constants.WAITING_PAY);
				insurance.setCreateTime(new Date());
				//String insuranceNo=insuranceSaver.saveInsuranceByBOrder(bOrder, passenger);
				insurance.setInsuranceNo("1111111");
				
				insurances.add(insurance);
			}
				passenger.setInsurances(insurances);
			}
			list.add(passenger);
		}	
		bOrder.setTaxStatistics(totalFee);
		bOrder.setPassengers(list);
		String carrier=flight_no.substring(0, 2);
		String pnr=createPnr(flights, list, carrier, contactMob, identity);
		bOrder.setPnr(pnr);
		if(isHaveChd){
			String chdPnr=createChdPnr(flights, list, carrier, contactMob, identity);
			bOrder.setCpnr(chdPnr);
		}
		return bOrder;
	}
	
	public static String createPnr(Set<Flight> flights,Set<Passenger> list,String carrier,String contactMob,String identity)throws Exception{
		
		StringBuffer createPnr=new StringBuffer();
		
		Date tktl= DateUtils.addHours(new Date(), 1);
		
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		
		SimpleDateFormat hm=new SimpleDateFormat("hhmm");
		
		createPnr.append("<?xml version='1.0'?><ABE_CreatePNR_1_2><TicketLimitDate>"+dateFormat.format(tktl)+"</TicketLimitDate><TicketLimitTime>"+hm.format(tktl)+"</TicketLimitTime><Office>can859</Office><Telephone/><RMKS><RMK/></RMKS><Flights>");
			
		for (Flight ft : flights) {
	
				createPnr.append("<Flight>");
				createPnr.append("<Carrier>"+ft.getCode().substring(0,2)+"</Carrier>");
				
				createPnr.append("<FlightNo>"+ft.getCode().substring(2, ft.getCode().length())+"</FlightNo>");
				createPnr.append("<ClassCode>"+ft.getCabin()+"</ClassCode>");
				createPnr.append("<DepartureDate>"+ft.getArrDay()+"</DepartureDate>");

				createPnr.append("<DepartureTime>"+ft.getDepTime().replace(":", "")+"</DepartureTime>");
				createPnr.append("<BoardPoint>"+ft.getDep()+"</BoardPoint>");

				createPnr.append("<OffPoint>"+ft.getArr()+"</OffPoint>");
			
				createPnr.append("</Flight>");
			
			}
			createPnr.append("</Flights>");
			createPnr.append("<Passengers>");
		
			for (Passenger passenger : list) {
				
				
				String passengerName=passenger.getName();
				if(!passenger.getAgeType().equalsIgnoreCase("CHD")){
					createPnr.append("<Passenger>");
					createPnr.append("<Name>"+passengerName+"</Name>");
					createPnr.append("<BirthDay>"+DateUtil.convertDateToString(passenger.getBirthday())+"</BirthDay>");
					createPnr.append("<Country>CN</Country>");
					createPnr.append("<CardNo></CardNo>");
					createPnr.append("<MobilePhone>"+contactMob+"</MobilePhone>");
					createPnr.append("<CarrierCard></CarrierCard>");
					createPnr.append("</Passenger>");
				}
			}
			createPnr.append("</Passengers>");
			
			createPnr.append("<OtherSegments>");
			
			int i=1;
			Locale l = new Locale("en");
			String day = String.format("%td", tktl);
			String month = String.format(l,"%tb", tktl);
			createPnr.append("<OtherSegment>CT 61223781 </OtherSegment>");
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				Passenger passenger = (Passenger) iterator.next();
				if(!passenger.getAgeType().equalsIgnoreCase("CHD")){
				createPnr.append("<OtherSegment>SSR FOID "+carrier+" HK/NI"+passenger.getCardNum()+"/P"+i+" </OtherSegment>");
				if(!iterator.hasNext()&&(carrier.equalsIgnoreCase("CZ")||carrier.equalsIgnoreCase("HU"))){
					createPnr.append("<OtherSegment>OSI "+carrier+" CTCT "+contactMob+" </OtherSegment>");
				}
				i++;
				}
			}
			
			createPnr.append("</OtherSegments>");
			createPnr.append("</ABE_CreatePNR_1_2>");

			String filter = "";
			ClientService<ServiceSoap> clientService = new ClientService<ServiceSoap>();

			ServiceSoap service = clientService.getClient("abeService.path",ServiceSoap.class);
			//ABE_AVDataset_1_3 查询单条航班信息
			System.out.println(createPnr.toString());
			String result="";
			try{
			 result = service.abeSubmit(identity, createPnr.toString(), filter);
			}catch(Exception e){
				logger.equals(e);
				throw new RuntimeException(e.getMessage());
			}
			String pnr=AbeUtil.changePnr(result);
		
		return pnr;
	}
	
public static String createChdPnr(Set<Flight> flights,Set<Passenger> list,String carrier,String contactMob,String identity) throws Exception{
		
		StringBuffer createPnr=new StringBuffer();
		
		Date tktl= DateUtils.addHours(new Date(), 1);
		
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		
		SimpleDateFormat hm=new SimpleDateFormat("HHmm");
		
		createPnr.append("<?xml version='1.0'?><ABE_CreatePNR_1_2><TicketLimitDate>"+dateFormat.format(tktl)+"</TicketLimitDate><TicketLimitTime>"+hm.format(tktl)+"</TicketLimitTime><Office>can859</Office><Telephone/><RMKS><RMK/></RMKS><Flights>");
			
		for (Flight ft : flights) {
	
				createPnr.append("<Flight>");
				createPnr.append("<Carrier>"+ft.getCode().substring(0,2)+"</Carrier>");
				
				createPnr.append("<FlightNo>"+ft.getCode().substring(2, ft.getCode().length())+"</FlightNo>");
				createPnr.append("<ClassCode>"+ft.getCabin()+"</ClassCode>");
				createPnr.append("<DepartureDate>"+ft.getArrDay()+"</DepartureDate>");

				createPnr.append("<DepartureTime>"+ft.getDepTime().replace(":", "")+"</DepartureTime>");
				createPnr.append("<BoardPoint>"+ft.getDep()+"</BoardPoint>");

				createPnr.append("<OffPoint>"+ft.getArr()+"</OffPoint>");
			
				createPnr.append("</Flight>");
			
			}
			createPnr.append("</Flights>");
			createPnr.append("<Passengers>");
		
			for (Passenger passenger : list) {
				
				
				String passengerName=passenger.getName();
				if(passenger.getAgeType().equalsIgnoreCase("CHD")){
				createPnr.append("<Passenger>");
				passengerName+="CHD";
				
				createPnr.append("<Name>"+passengerName+"</Name>");
				createPnr.append("<BirthDay>"+DateUtil.convertDateToString(passenger.getBirthday())+"</BirthDay>");
				createPnr.append("<Country>CN</Country>");
				createPnr.append("<CardNo></CardNo>");
				createPnr.append("<MobilePhone>"+contactMob+"</MobilePhone>");
				createPnr.append("<CarrierCard></CarrierCard>");
				createPnr.append("</Passenger>");
				}
			}
			createPnr.append("</Passengers>");
			createPnr.append("<OtherSegments>");
			int i=1;
			Locale l = new Locale("en");
			String day = String.format("%td", tktl);
			String month = String.format(l,"%tb", tktl);
			createPnr.append("<OtherSegment>CT 61223781 </OtherSegment>");
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				Passenger passenger = (Passenger) iterator.next();
				if(passenger.getAgeType().equalsIgnoreCase("CHD")){
					createPnr.append("<OtherSegment>SSR FOID "+carrier+" HK/NI"+passenger.getCardNum()+"/P"+i+" </OtherSegment>");
					if(!iterator.hasNext()&&(carrier.equalsIgnoreCase("CZ")||carrier.equalsIgnoreCase("HU"))){
						createPnr.append("<OtherSegment>OSI "+carrier+" CTCT "+contactMob+" </OtherSegment>");
					}
					i++;
				}
			}
			
			createPnr.append("</OtherSegments>");
			createPnr.append("</ABE_CreatePNR_1_2>");

			String filter = "";
			ClientService<ServiceSoap> clientService = new ClientService<ServiceSoap>();

			ServiceSoap service = clientService.getClient("abeService.path",ServiceSoap.class);
			//ABE_AVDataset_1_3 查询单条航班信息
			System.out.println(createPnr.toString());
			String result="";
			try{
			 result = service.abeSubmit(identity, createPnr.toString(), filter);
			}catch(Exception e){
				logger.equals(e);
				throw new RuntimeException(e.getMessage());
			}
			String pnr=AbeUtil.changePnr(result);
		
		return pnr;
	}
}
